package com.zzq.order.service.impl;


import com.github.yulichang.base.MPJBaseServiceImpl;
import com.zzq.common.core.utils.DateUtils;
import com.zzq.common.core.utils.uuid.IdUtils;
import com.zzq.common.rpc.GoodsRpcService;
import com.zzq.order.domain.MyOrder;
import com.zzq.order.mapper.OrderMapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
@RefreshScope
public class OrderServiceImpl extends MPJBaseServiceImpl<OrderMapper, MyOrder> {

    @DubboReference(check = false, version = "1.0.0")
    private GoodsRpcService goodsRpcService;

    @GlobalTransactional(name = "order-insertOrder",timeoutMills = 10000)
    public Boolean insertOrder(MyOrder myOrder) {
        Boolean orderResult = createOrder(myOrder);
        Boolean goodsResult = goodsRpcService.reduceStock(myOrder.getGoodsId(), myOrder.getGoodsCount());
        if (orderResult && goodsResult) {
            //第三步更新订单状态
           return updataOrderStatus(myOrder, "1");
        }
        return false;
    }

    private Boolean createOrder(MyOrder myOrder) {
        String id = IdUtils.fastSimpleUUID();
        myOrder.setId(id);
        myOrder.setOrderNum(DateUtils.dateTimeNow() + id);
        myOrder.setOrderName("订单" + myOrder.getOrderNum());
        myOrder.setOrderStatus("0");
        return save(myOrder);
    }

    public boolean updataOrderStatus(MyOrder myOrder, String orderStatus) {
        myOrder.setOrderStatus(orderStatus);
        return saveOrUpdate(myOrder);
    }


}
